﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Diagnostics;
using BackgrounderService.ServiceReference1;

namespace BackgrounderService
{
    class Account
    {
        public Account(string username, string password)
        {
            Username = username;
            Password = password;
        }
        public string Username { get; private set;}
        public string Password { get; private set;}
    }

    class UploadArgs
    {
        public UploadArgs(DateTime Time,ServiceReference1.DataType type)
        {
            this.Time=Time;
            this.type = type;
        }
        public DateTime Time;
        public string TableName
        {
            get
            {
                switch (this.type)
                {
                    case DataType.Mouse:
                        {
                            return "MouseRecords";
                        }
                    case DataType.Key:
                        {
                            return "KeyRecords";
                        }
                    case DataType.SysInfo:
                        return "SysPerfRecords";
                    default:
                        throw new SystemException("Type Error");
                }
            }
        }
        public DataType type;

    }

    class UploadModel
    {
        public delegate void UploadFinishHandler(bool IsSuccess,DataType type,TimeSpan UsedTime,string Infomation);

        public event UploadFinishHandler OnUploadFinish;

        public void BeginUpload(Account account,DataType type)
        {
            BeginUploadDelegate Fun =
                delegate()
                {
                    lock (Lock)
                    {
                        using (var Client = new PCHMSServiceClient())
                        {
                            Stream s = null;
                            try
                            {
                                DateTime start = DateTime.Now;
                                var SessionId = Client.RequestSession(account.Username, account.Password);
                                var Date = Client.RequestUploadRecords(SessionId, type);
                                //System.Windows.Forms.MessageBox.Show(Date.ToString());
                                var Args = new UploadArgs((DateTime)Date, type);
                                s = PrepareData(Args);
                                Client.Upload(SessionId, type, s);
                                OnUploadFinish.Invoke(true, type, DateTime.Now - start, "");
                            }
                            catch (System.Exception ex)
                            {
                                OnUploadFinish.Invoke(false, type, new TimeSpan(0), ex.Message);
                            }
                            finally
                            {
                                Client.Close();
                                if (s != null)
                                    s.Close();
                            }

                        }
                    }        
                };
            Fun.BeginInvoke(null, null);
        }

        public Stream PrepareData(UploadArgs Args)
        {
            StringBuilder SQL = new StringBuilder();
            SQL.Append("select * from "+Args.TableName+" where timestamp>'"+Args.Time.ToString("yyyy-MM-dd HH:mm:ss")+"';");
            //System.Windows.Forms.MessageBox.Show(MouseSQL.ToString());
            if (false)
            {

            }
            StringBuilder ShellCmd = new StringBuilder();
            ShellCmd.AppendLine(".output " + Args.TableName);
            ShellCmd.AppendLine(".separator '\t'");
            ShellCmd.AppendLine(SQL.ToString());
            ShellCmd.AppendLine(".exit");

            Process p = new Process();
            p.StartInfo.FileName = "sqlite3.exe";
            p.StartInfo.Arguments = "database.db";
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.RedirectStandardInput = true;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.RedirectStandardError = true;
            p.StartInfo.CreateNoWindow = true;
            p.Start();
            p.StandardInput.Write(ShellCmd.ToString());
            if (!p.WaitForExit(20000))
            {
                throw new SystemException("Sqlite3.exe error");
            }
            var s = new FileStream(Args.TableName, FileMode.Open);
            return s;
        }

        private delegate void BeginUploadDelegate();

        private object Lock = new object();
    }

}
